package android.handler;

import java.util.Iterator;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author Ajie
 * @date 2021-03-15
 * @function
 */
public class MessageQueue {
    LinkedBlockingQueue<Message> queue = new LinkedBlockingQueue<>();

    public void enqueueMessage(Message msg){
        try {
            queue.put(msg);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    // 从消息队列中取出消息
    public Message next(){
        try {
            return queue.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void removeMessages(Handler h, int what) {
        if (h == null) {
            return;
        }
        synchronized (this) {
            Iterator<Message> iterator = queue.iterator();
            while (iterator.hasNext()){
                Message next = iterator.next();
                if (next!=null && what==next.what){
                    iterator.remove();
                }
            }
        }
    }
//    public void removeMessages(Handler h, int what, Object object) {
//        if (h == null) {
//            return;
//        }
//
//        synchronized (this) {
//
//        }
//    }
}
